'use strict';
var io = require('../IOUtils');
var get_filepath = require('../functions/get_filepath.js');

function webhook () {
  return function (req, res, next) {


    console.log('webhook' + JSON.stringify(req.query));

    var cmdStr = 'git pull';
    exec(cd2MarkDownDir(cmdStr));

    res.json({
      status: 0,
      message: JSON.stringify(req.query) + io.getRootPath(),
    });
  };

  function cd2MarkDownDir (cmd) {

    var dir = io.getMDRootPath();
    var cd2dir = '';
    if (dir.lastIndexOf(':') > 0) {
      cd2dir += dir.substring(0, 2) + ' && ' + 'cd ' + dir;
      console.log('[INFO] win path' + cd2dir);
    } else {
      cd2dir = 'cd ' + dir;
    }
    cmd = cd2dir + ' && ' + cmd;
    return cmd;
  }

  function exec (cmd) {
    console.log('[INFO] cmd ' + cmd);
    require('child_process').exec(cmd, function (error, stdout, stderr) {
      console.log('[INFO]  >: ' + cmd + '\r\n[stdout]:' + stdout + '\r\n[stderr]:' + stderr + '\r\n[error]:' + error);
    });
  }
}

// Exports
module.exports = webhook;
